package com.kuang.Controller;

import com.kuang.dao.DepartmentDao;
import com.kuang.dao.EmployeeDao;
import com.kuang.pojo.Department;
import com.kuang.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao dao;

    @Autowired
    DepartmentDao departmentDao;

    @RequestMapping("/getAllEmp")
    public String list(Model model) {
        Collection<Employee> all = dao.getAll();
        model.addAttribute("emps", all);
        return "list";
    }

    @GetMapping("/emp")
    public String toAddPage(Model model) {
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);
        return "add";
    }

    @RequestMapping("/emp")
    public String addEmp(Employee emp) {
        //添加操作
        dao.save(emp);
        return "redirect:/getAllEmp";
    }

    //跳转到员工修改页面
    @GetMapping("/toUpdate/{id}")
    public String toUpdateEmp(@PathVariable("id") Integer id, Model Model) {
        //查出原来的数据
        Employee employeeById = dao.getEmployeeById(id);
        Collection<Department> departments = departmentDao.getDepartments();
        Model.addAttribute("emp", employeeById);
        Model.addAttribute("depts", departments);
        return "update";
    }

    //修改员工信息
    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee) {
        dao.save(employee);
        return "redirect:/getAllEmp";
    }

    //删除员工
    @GetMapping("/delEmp/{id}")
    public String delEmp(@PathVariable("id") Integer id) {
        dao.deleteEmployeeById(id);
        return "redirect:/getAllEmp";
    }
}
